import os
import platform
import subprocess

import wx
import wx.gizmos as gizmos

#from common import LogEvent
from config import DATA_DIR_QUOTES, DATA_TASKS


class StrategyPanel(wx.Panel):
    def __init__(self, parent):
        from core.backtrader_extends.task import local_tasks
        super(StrategyPanel, self).__init__(parent)
        items = [

        ]
        for t in local_tasks.keys():
            items.append({"name":t,'task': local_tasks[t]})
        self.strategies = {
            "自有策略": items,
            # "公开策略": [
            #     {"name": "双均线"},
            #     {"name": "布林带"}
            # ]
        }
        self.init_ui()

    def init_ui(self):
        sizer = wx.BoxSizer(wx.VERTICAL)

        # 策略列表标题
        title = wx.StaticText(self, label="策略管理", style=wx.ALIGN_CENTER)
        title.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
        sizer.Add(title, 0, wx.EXPAND | wx.ALL, 5)

        # 创建TreeListCtrl
        self.tree_list = gizmos.TreeListCtrl(self, style=
        wx.TR_DEFAULT_STYLE
        | wx.TR_HIDE_ROOT
        | wx.TR_FULL_ROW_HIGHLIGHT
        | wx.TR_ROW_LINES
                                             )

        # 添加列
        self.tree_list.AddColumn("策略名称", width=150)
        # self.tree_list.AddColumn("状态", width=80)
        # self.tree_list.AddColumn("收益率(%)", width=80)
        # self.tree_list.AddColumn("持仓", width=80)

        # 设置根节点
        root = self.tree_list.AddRoot("策略根节点")
        # 绑定双击事件
        self.tree_list.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.on_item_double_click)

        # 加载策略数据
        self.load_strategies()

        sizer.Add(self.tree_list, 1, wx.EXPAND | wx.ALL, 5)

        # 策略操作按钮
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.open_btn = wx.Button(self, label="策略目录")
        self.reload_btn = wx.Button(self, label="重新加载")
        # self.edit_btn = wx.Button(self, label="编辑策略")
        # self.delete_btn = wx.Button(self, label="删除策略")
        # self.start_btn = wx.Button(self, label="启动策略")
        # self.stop_btn = wx.Button(self, label="停止策略")

        btn_sizer.Add(self.open_btn, 0,  wx.ALIGN_LEFT |wx.RIGHT, 5)
        btn_sizer.Add(self.reload_btn, 0, wx.ALIGN_LEFT | wx.RIGHT, 5)
        # btn_sizer.Add(self.edit_btn, 0, wx.RIGHT, 5)
        # btn_sizer.Add(self.delete_btn, 0, wx.RIGHT, 5)
        # btn_sizer.Add(self.start_btn, 0, wx.RIGHT, 5)
        # btn_sizer.Add(self.stop_btn, 0)

        sizer.Add(btn_sizer, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)

        self.SetSizer(sizer)

        # 绑定事件
        self.open_btn.Bind(wx.EVT_BUTTON, self.open_task_dir)
        self.reload_btn.Bind(wx.EVT_BUTTON, self.reload_tasks)
        # self.edit_btn.Bind(wx.EVT_BUTTON,
        #                    lambda e: wx.PostEvent(self.GetParent(), LogEvent(message="编辑策略按钮点击")))
        # self.delete_btn.Bind(wx.EVT_BUTTON,
        #                      lambda e: wx.PostEvent(self.GetParent(), LogEvent(message="删除策略按钮点击")))
        # self.start_btn.Bind(wx.EVT_BUTTON,
        #                     lambda e: wx.PostEvent(self.GetParent(), LogEvent(message="启动策略按钮点击")))
        # self.stop_btn.Bind(wx.EVT_BUTTON,
        #                    lambda e: wx.PostEvent(self.GetParent(), LogEvent(message="停止策略按钮点击")))
        # #self.tree_list.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.on_item_activated)

    def reload_tasks(self, event):
        self.load_strategies()
        wx.MessageBox('重新加载策略列表成功！')

    def open_task_dir(self, event):
        # 指定要打开的目录路径
        from config import DATA_TASKS

        # 检查目录是否存在
        target_dir = str(DATA_TASKS.resolve())
        if not os.path.exists(str(DATA_TASKS.resolve())):
            wx.MessageBox(f"目录不存在: {target_dir}", "错误", wx.OK | wx.ICON_ERROR)
            return

        # 根据不同操作系统打开目录
        system = platform.system()
        try:
            if system == "Windows":
                os.startfile(target_dir)
            elif system == "Darwin":  # macOS
                os.system(f'open "{target_dir}"')
            else:  # Linux
                os.system(f'xdg-open "{target_dir}"')
        except Exception as e:
            wx.MessageBox(f"无法打开目录: {str(e)}", "错误", wx.OK | wx.ICON_ERROR)

    def on_item_double_click(self, event):
        item = event.GetItem()
        item_data = self.tree_list.GetItemPyData(item)  # 修改为GetItemPyData
        if item_data and item_data["type"] == "strategy":
            data = item_data["data"]
            file_path = DATA_TASKS.joinpath(data['name'] + '.toml')
            self.open_file_with_default_editor(str(file_path.resolve()))
            # wx.PostEvent(self.GetParent(), LogEvent(
            #     message=f"双击策略: {strategy['name']}"
            # ))

    def load_strategies(self):
        """加载策略到树形列表"""
        self.tree_list.DeleteAllItems()
        # 添加根节点（TreeListCtrl需要根节点）
        root = self.tree_list.AddRoot("所有策略")

        #root = self.tree_list.GetRootItem()

        # 添加分类节点
        private_node = self.tree_list.AppendItem(root, "公开策略")
        public_node = self.tree_list.AppendItem(root, "自有策略")

        # 添加自有策略
        for strategy in self.strategies["自有策略"]:
            item = self.tree_list.AppendItem(private_node, strategy["name"])
            # self.tree_list.SetItemText(item, strategy["status"], 1)
            # self.tree_list.SetItemText(item, f"{strategy.get('return', 0):.2f}", 2)
            # self.tree_list.SetItemText(item, str(strategy.get("position", 0)), 3)
            self.tree_list.SetItemPyData(item, {"type": "strategy", "data": strategy})  # 修改为SetItemPyData

        # 添加公开策略
        # for strategy in self.strategies["公开策略"]:
        #     item = self.tree_list.AppendItem(public_node, strategy["name"])
        #     # self.tree_list.SetItemText(item, strategy["status"], 1)
        #     # self.tree_list.SetItemText(item, f"{strategy.get('return', 0):.2f}", 2)
        #     # self.tree_list.SetItemText(item, str(strategy.get("position", 0)), 3)
        #     self.tree_list.SetItemPyData(item, {"type": "strategy", "data": strategy})  # 修改为SetItemPyData

        # 展开所有节点
        self.tree_list.ExpandAll()



    def open_file_with_default_editor(self, file_path):
        """用系统默认编辑器打开文件"""
        if not os.path.exists(file_path):
            wx.MessageBox(f"文件不存在: {file_path}", "错误", wx.OK | wx.ICON_ERROR)
            return

        try:
            if platform.system() == "Windows":
                os.startfile(file_path)
            elif platform.system() == "Darwin":  # macOS
                subprocess.run(["open", file_path])
            else:  # Linux
                subprocess.run(["xdg-open", file_path])
        except Exception as e:
            wx.MessageBox(f"无法打开文件: {str(e)}", "错误", wx.OK | wx.ICON_ERROR)